package com.theme.passport.controller.theme;

import com.theme.common.base.ConfigConstant;
import com.theme.common.mvc.exception.RRException;
import com.theme.common.mvc.utils.PageUtils;
import com.theme.common.mvc.view.R;
import com.theme.passport.controller.oss.cloud.OSSFactory;
import com.theme.passport.controller.sys.AbstractController;
import com.theme.passport.entity.SysRoleEntity;
import com.theme.passport.entity.SysUserEntity;
import com.theme.passport.entity.constant.SysRoleNameEnum;
import com.theme.passport.entity.constant.ThemeNtsEnum;
import com.theme.passport.entity.theme.WallpaperEntity;
import com.theme.passport.service.SysRoleService;
import com.theme.passport.service.SysUserRoleService;
import com.theme.passport.service.SysUserService;
import com.theme.passport.service.theme.WallpaperService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;


/**
 * 壁纸表
 *
 * @author live
 * @email 870459550@qq.com
 * @date 2022-06-21 10:01:49
 */
@RestController
@RequestMapping("wallpaper/wallpaper")
public class WallpaperController extends AbstractController {
    @Autowired
    private WallpaperService wallpaperService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("wallpaper:wallpaper:list")
    public R list(@RequestParam Map<String, Object> params){
        // 根据用户查询用户角色，如果是设计师就查询他的，不是则查询所有的
        SysUserEntity user = getUser();
        List<Long> roleIdList = sysUserRoleService.queryRoleIdList(user.getUserId());
        if (roleIdList != null && roleIdList.size() == 1){
            Long userRoleId = roleIdList.get(0) ;
            List<SysRoleEntity> sysRoleList = sysRoleService.queryRoleListByName(SysRoleNameEnum.DESIGNER.getName());
            if (sysRoleList != null && sysRoleList.size() == 1){
                SysRoleEntity sysRoleEntity = sysRoleList.get(0);
                if (sysRoleEntity.getRoleId().equals(userRoleId)){
                    params.put("userId",user.getUserId() +"");
                }
            }
        }
        PageUtils page = wallpaperService.queryPage(params);
        List<WallpaperEntity> list = (List<WallpaperEntity>) page.getList();
        list.forEach(wallpaper ->{
            SysUserEntity byId = sysUserService.getById(wallpaper.getUserId());
            wallpaper.setUseNickname(byId.getNickname());
            String label = wallpaper.getLabel();
            if (label != null){
                String[] split = label.split(",");
                wallpaper.setLabels(Arrays.asList(split));
            }
        });
        page.setList(list);
        return R.ok().put("page", page);
    }

    /**
     * 列表
     */
    @RequestMapping("/listItem")
    @RequiresPermissions("wallpaper:wallpaper:list")
    public R listItem(@RequestParam Map<String, Object> params) {
        SysUserEntity user = getUser();
        params.put("userId",user.getUserId());
        PageUtils page = wallpaperService.queryPageByStatus(params);
        List<WallpaperEntity> list = (List<WallpaperEntity>) page.getList();
        list.forEach(theme ->{
            SysUserEntity byId = sysUserService.getById(theme.getUserId());
            theme.setUseNickname(byId.getNickname());
        });
        page.setList(list);
        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("wallpaper:wallpaper:info")
    public R info(@PathVariable("id") Long id){
		WallpaperEntity wallpaper = wallpaperService.getById(id);
        SysUserEntity byId = sysUserService.getById(wallpaper.getUserId());
        wallpaper.setUseNickname(byId.getNickname());
        String label = wallpaper.getLabel();
        if (label != null){
            String[] split = label.split(",");
            wallpaper.setLabels(Arrays.asList(split));
        }
        return R.ok().put("wallpaper", wallpaper);
    }

//    /**
//     * 保存
//     */
//    @RequestMapping("/save")
//    @RequiresPermissions("wallpaper:wallpaper:save")
//    public R save(@RequestBody WallpaperEntity wallpaper){
//        wallpaper.setCreated(new Date());
//        SysUserEntity user = getUser();
//        wallpaper.setUserId(user.getUserId());
//
//        //1.判断主题名称是否已经存在
//        String name = wallpaper.getName();
//        QueryWrapper<WallpaperEntity> nameWrapper = new QueryWrapper<>();
//        nameWrapper.and(wrapper -> wrapper
//                .eq("name", name));
//        List<WallpaperEntity> nameList = wallpaperService.list(nameWrapper);
//        if (nameList != null && nameList.size() >0 ){
//            return R.error("该壁纸名称已存在,请更改壁纸名称!");
//        }
//        wallpaper.setStatus(ThemeStatusEnum.SHELVES.getValue());
//        R r = wallpaperService.saveWallpaper(wallpaper);
//        return r;
//    }

    /**
     * 新版添加多张
     */
    @RequestMapping("/save2")
    @RequiresPermissions("wallpaper:wallpaper:save")
    public R save2(@RequestBody WallpaperEntity wallpaper){
        List<String> imageList = wallpaper.getImages();
        if (imageList == null || imageList.size() <=0){
            return R.error("该壁纸为空,请确认后重新上传!");
        }
        String label = "";
        List<String> labels = wallpaper.getLabels();
        if (labels != null && labels.size() > 0){
            label = parseListToStr(labels);
        }
        List<WallpaperEntity> listWallpaper = new ArrayList<>();
        String finalLabel = label;
        imageList.forEach(image -> {
            WallpaperEntity wallpaperTemp = new WallpaperEntity();
            wallpaperTemp.setImage(image);
            wallpaperTemp.setLabel(finalLabel);
            wallpaperTemp.setCreated(new Date());
            wallpaperTemp.setUpdated(new Date());
            SysUserEntity user = getUser();
            wallpaperTemp.setUserId(user.getUserId());
            wallpaperTemp.setName(wallpaper.getName());
            wallpaperTemp.setClassifyId(wallpaper.getClassifyId());
            wallpaperTemp.setClassifyName(wallpaper.getClassifyName());
            wallpaperTemp.setFree(wallpaper.getFree());
            wallpaperTemp.setStatus(wallpaper.getStatus());
            listWallpaper.add(wallpaperTemp);
        });
        wallpaperService.saveBatch(listWallpaper);
        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("wallpaper:wallpaper:update")
    public R update(@RequestBody WallpaperEntity wallpaper){

        //TODO 如果修改状态的并且为下架的话-查询组件属不属于今日推荐

        //TODO 如果修改状态的并且为下架的话-查询组件属不属于专题

        List<String> labels = wallpaper.getLabels();
        if (labels != null && labels.size() > 0){
            String label = parseListToStr(labels);
            wallpaper.setLabel(label);
        }
        wallpaper.setNts(ThemeNtsEnum.YES.getValue());
        wallpaper.setUpdated(new Date());
        wallpaperService.updateWallpaper(wallpaper);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("wallpaper:wallpaper:delete")
    public R delete(@RequestBody Long[] ids){
        //TODO 查询主题属不属于今日推荐

        //TODO 查询主题属不属于专题

		wallpaperService.removeByIds(Arrays.asList(ids));
        return R.ok();
    }

    /**
     * 上传图片文件
     */
    @PostMapping("/upload")
    public R upload(@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new RRException("上传文件不能为空");
        }

        String originalFilename = file.getOriginalFilename();
        String fileExpandName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
        if (!ConfigConstant.filePattern.matcher(fileExpandName.toUpperCase()).find()) {
            return R.error("文件格式不支持");
        }

        //上传文件
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String url = OSSFactory.build(null).uploadSuffix(file.getBytes(), suffix);

        return R.ok().put("filePath", url);
    }

    public static <T> String parseListToStr(List<T> list){
        String result = list.stream().map(String::valueOf).collect(Collectors.joining(","));
        return result;
    }
}
